<template>
  <div>
    <div class="app-container">
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd" :disabled="status">新增竞标规则</el-button>
        </el-col>
        <right-toolbar @queryTable="getList"></right-toolbar>
      </el-row>
      <el-table v-loading="loading" :data="bidRulesList" :default-sort = "{prop: 'createTime', order: 'ascending'}">
        <el-table-column label="序号" type="index" align="center" width="50"/>
        <el-table-column label="最小降幅" align="center" class-name="small-padding" width="80">
          <template slot-scope="scope">
            {{scope.row.minDecline}}%
          </template>
        </el-table-column>
        <el-table-column label="最大降幅" align="center" class-name="small-padding" width="80">
          <template slot-scope="scope">
            {{scope.row.maxDecline}}%
          </template>
        </el-table-column>
        <el-table-column label="竞标类别" align="center" prop="biddingCategory" width="80"/>
        <el-table-column label="货币类别" align="center" prop="currencyCategory" width="80"/>
        <el-table-column label="相同报价排名" align="center" prop="sorted" width="70"/>
        <el-table-column label="延长时间" align="center" class-name="small-padding" width="80">
          <template slot-scope="scope">
            {{scope.row.extendTime}}分钟
          </template>
        </el-table-column>
        <el-table-column label="延长次数" align="center" prop="extendCount" width="80"/>
        <el-table-column label="竞价类别" align="center" prop="priceCategory" width="80"/>
        <el-table-column label="小数保留位数" align="center" prop="decimalPlaces" width="80"/>
        <el-table-column label="小数舍弃规则" align="center" prop="decimalRule" width="80"/>
        <el-table-column label="竞标方式" align="center" prop="biddingMethod"/>
        <el-table-column label="延时规则" align="center" prop="extendTimeRule"/>
        <el-table-column label="时间" align="center" prop="createTime" sortable width="100"/>
        <el-table-column label="操作" align="center" class-name="small-padding" width="70">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
            >编辑</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />

      <!-- 添加或修改中标候选人对话框 -->
      <el-dialog :title="title" :visible.sync="open" width="1080px" append-to-body>
        <el-form ref="form" :model="form" :rules="rules" label-width="120px">
          <el-form-item label="最小降幅(%)" prop="minDecline" class="form-input">
            <el-input v-model="form.minDecline" placeholder="请输入最小降幅，如：0.25"/>
          </el-form-item>
          <el-form-item label="最大降幅(%)" prop="maxDecline" class="form-input">
            <el-input v-model="form.maxDecline" placeholder="请输入最小降幅，如：3.75"/>
          </el-form-item>
          <el-form-item label="竞标类别" prop="biddingCategory" class="form-input">
            <el-input v-model="form.biddingCategory" placeholder="请输入竞标类别" />
          </el-form-item>
          <el-form-item label="货币类别" prop="currencyCategory" class="form-input">
            <el-input v-model="form.currencyCategory" placeholder="请输入货币类别" />
          </el-form-item>
          <el-form-item label="相同报价排名" prop="sorted" class="form-input">
            <el-input v-model="form.sorted" placeholder="请输入相同报价排名" />
          </el-form-item>
          <el-form-item label="延长时间(分钟)" prop="extendTime" class="form-input">
            <el-input v-model="form.extendTime" placeholder="请输入延长时间" />
          </el-form-item>
          <el-form-item label="延长次数" prop="extendCount" class="form-input">
            <el-input v-model="form.extendCount" placeholder="请输入延长次数" />
          </el-form-item>
          <el-form-item label="竞价类别" prop="priceCategory" class="form-input">
            <el-input v-model="form.priceCategory" placeholder="请输入竞价类别" />
          </el-form-item>
          <el-form-item label="竞标方式">
            <el-radio-group v-model="form.biddingMethodRadio">
              <el-radio
                v-for="dict in dict.type.bidding_method"
                :key="dict.value"
                :label="dict.value"
              >{{dict.label}}</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="延时规则" prop="extendTimeRule" class="form-input">
            <el-input style="width: 880px" v-model="form.extendTimeRule" placeholder="请输入延时规则"/>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitForm"  :disabled="status">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { listBidRules, getBidRules, delBidRules, addBidRules, updateBidRules } from "@/api/system/tender/bidRules";
import {getToken} from "@/utils/auth";
import {findSubmission} from "@/api/system/tender/submission";
import {getSupplier} from "@/api/system/supplier";
import {updateTender} from '@/api/system/tender/tender'

export default {
  name: "bidRules",
  dicts: ['bidding_method'],
  data() {
    return {
      status:true,
      isType:null,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 中标候选人表格数据
      bidRulesList: [],
      //参与投标供应商数据
      submissionList:[],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        sid: null,
        hid: null,
        zFinal: null,
        zFraction: null,
        zRecommend: null,
        zRanking: null,
        zSign: null,
        zCensor: null,
        zReview: null,
        zSummary: null,
        zSendTime: null
      },
      queryParams2:{
        sid:null,
      },
      queryParams3:{
        sid:0,
        sCode:null,
        sName:null,
        sWay: null,
        sMust:null,
        sSway:null,
        sType: null,
        sBudget:null,
        sUnit:null,
        sPerson:null,
        sPhone:null,
        email:null,
        sAddress:null,
        fjFiles:null,
        sProjectState:null,
        sLeader:null,
      },
      // 表单参数
      form: {
        minDecline: '0.25',
        maxDecline: '3.75',
        biddingCategory: '降价竞标',
        currencyCategory: 'RMB',
        currencyUnit: '元',
        sorted: '按时间先后依次排名',
        extendTime: '1',
        extendCount: '99999',
        priceCategory: '竞总价',
        biddingMethod: '按供应商提供的初次报价竞标，每次输入的降幅为初始价格的百分比，排名以金额从小到大',
        biddingMethodRadio: "1",
        extendTimeRule: '当该供应商有最新报价，名次有变化，并且该供应商的名次属于预先设定的获的标案名次之内'
      },
      // 表单校验
      rules: {
        // hid: [
        //   { required: true, message: "供应商不能为空", trigger: "change" }
        // ],
        zFinal: [
          { required: true, message: "最终报价不能为空", trigger: "blur" }
        ],
        zFraction: [
          { required: true, message: "最终得分不能为空", trigger: "blur" }
        ],
        zRecommend: [
          { required: true, message: "是否推荐不能为空", trigger: "change" }
        ],
        zRanking: [
          { required: true, message: "排名不能为空！", trigger: "blur" },
          { required: true, message: "排名不能输入非数字！", trigger: "input" },
        ],
        zSendTime: [
          { required: true, message: "发送时间不能为空", trigger: "blur" }
        ],

      },
      // 收集——上传文件的列表(专家签到表)
      uploadFiles: [],
      // 收集——上传文件的个数(专家签到表)
      filesLength: 0,
      // 收集——上传文件的列表(审查表)
      uploadFiles2: [],
      // 收集——上传文件的个数(审查表)
      filesLength2: 0,
      // 收集——上传文件的列表(评审表)
      uploadFiles3: [],
      // 收集——上传文件的个数(评审表)
      filesLength3: 0,
      // 收集——上传文件的列表(最终汇总表)
      uploadFiles4: [],
      // 收集——上传文件的个数(最终汇总表)
      filesLength4: 0,
      // 上传参数
      upload: {
        // 上传的文件列表(专家签到表)
        fileList: [],
        // 上传的文件列表(审查表)
        fileList2: [],
        // 上传的文件列表(评审表)
        fileList3: [],
        // 上传的文件列表(最终汇总表)
        fileList4: [],
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: {
          Authorization: "Bearer " + getToken()
        },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/bidding/documents/upload1",
      }
    };
  },
  created() {
    this.queryParams.sid = this.$route.query.sid;
    this.getList();

    this.queryParams2.sid = this.$route.query.sid;
    //this.getSubmission();
    //getTender(this.queryParams.sid).then(res=>{
      //if(res.data.sProjectState === 7){
        //this.status=true;
      //}
    //});
  },
  methods: {
    //是否推荐下拉框改变
    changeSelect3(value){
      //根据id拿供应商
      getSupplier(value).then(res=>{
        //获取供应商名称
        this.form.hName = res.data.hName;
      });
    },
    //是否推荐下拉框改变
    changeSelect1(value){
      this.form.zRecommend = value;
      //根据id拿供应商
      getSupplier(this.form.hid).then(res=>{
        //获取供应商名称
        this.form.hName = res.data.hName;
      });
    },
    /** 查询竞标规则列表 */
    getList() {
      this.loading = true;
      listBidRules(this.queryParams).then(response => {
        this.bidRulesList = response.rows;
        this.total = response.total;
        if(this.total > 0){
          this.status = true;
        }else{
          this.status = false;
        }
        this.loading = false;
      });
    },
    //查询参与投标供应商
    getSubmission(){
      findSubmission(this.queryParams2.sid).then(res=>{
        this.submissionList = res.data;
      });
    },
    // 取消按钮
    cancel() {
      this.status=true;
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        uid: null,
        sid: null,
        minDecline: null,
        maxDecline: null,
        biddingCategory: null,
        currencyCategory: null,
        currencyUnit: null,
        sorted: null,
        extendTime: null,
        extendCount: null,
        priceCategory: null,
        biddingMethod: null,
        biddingMethodRadio: null,
        extendTimeRule: null
      };
    },
    getLabelText(value) {
      const labels = {
        1: '按供应商提供的初次报价竞标，每次输入的降幅为初始价格的百分比，排名以金额从小到大',
        2: '按供应商提供的初次报价竞标，每次输入的降幅为初始价格的百分比，排名以累计降幅从大到小'
      };
      return labels[value] || '按供应商提供的初次报价竞标，每次输入的降幅为初始价格的百分比，排名以金额从小到大';
    },
    resetAdd() {
      this.form = {
        id: null,
        uid: null,
        sid: null,
        minDecline: '0.25',
        maxDecline: '3.75',
        biddingCategory: '降价竞标',
        currencyCategory: 'RMB',
        currencyUnit: "元",
        sorted: '按时间先后依次排名',
        extendTime: '1',
        extendCount: '99999',
        priceCategory: '竞总价',
        biddingMethod: '按供应商提供的初次报价竞标，每次输入的降幅为初始价格的百分比，排名以金额从小到大',
        biddingMethodRadio: "1",
        extendTimeRule: '当该供应商有最新报价，名次有变化，并且该供应商的名次属于预先设定的获的标案名次之内'
      };
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.resetAdd();
      this.isType = "add";
      this.form.sid =this.$route.query.sid;
      this.form.sCode =this.$route.query.sCode;
      this.form.decimalPlaces=4;//
      this.form.decimalRule='四舍五入';
      this.open = true;
      this.title = "添加竞标规则";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.status=false;
      this.isType = "update";
      const id = row.id || this.ids
      getBidRules(id).then(response => {
        this.form = response.data;
        if(response.data.biddingMethodRadio){
          this.form.biddingMethodRadio = response.data.biddingMethodRadio.toString();
        }
        this.open = true;
        this.title = "修改竞标规则";
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除中标候选人编号为"' + ids + '"的数据项？').then(function() {
        return delBidRules(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        //表单验证
        if (valid) {
          if( this.filesLength === 0 && this.filesLength2 === 0 && this.filesLength3=== 0 && this.filesLength4 === 0){
            //判断type值  update：修改  add：新增
            const radioValue = this.form.biddingMethodRadio;
            this.form.biddingMethod = this.getLabelText(radioValue);
            if (this.isType === 'update') {
              updateBidRules(this.form).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else if(this.isType === 'add'){
              this.form.sid = this.$route.query.sid;//确定对应招标项目
              addBidRules(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
            //修改招标项目状态
            this.upTender();
            this.cancel();
          }else{
            if(this.filesLength > 0 && this.form.zSign == null){
              this.$refs.upload.submit();
            }else
            if(this.filesLength2 > 0 && this.form.zCensor == null){
              this.$refs.upload2.submit();
            }else
            if(this.filesLength3 > 0 && this.form.zReview == null){
              this.$refs.upload3.submit();
            }else
            if(this.filesLength4 > 0 && this.form.zSummary == null){
              this.$refs.upload4.submit();
            }
          }
        }
      });
    },
    //修改招标项目状态(=>定标中)
    upTender(){
      //判断中标候选人是否至少三人
      this.queryParams.sid = this.$route.query.sid;
      listBidRules(this.queryParams).then(response => {
        if(response.rows.length > 2){
          this.queryParams3.sid = this.$route.query.sid;
          this.queryParams3.sProjectState = 6;//定标中
          //修改招标项目状态
          updateTender(this.queryParams3).then(r=>{});
        }
      });

    },
    /** 专家签到表 */
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 修改当前文件列表长度
    changeFileLength(file, fileList){
      this.filesLength = fileList.length;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.uploadFiles.push(file);
      //每上传完一个文件都会执行该函数，所以必须等上传完成后再提交表单
      if (this.uploadFiles.length === this.filesLength){
        //已上传文件  --> 字符串
        let updatedArray = fileList.map(obj => {
          let newObj = obj;
          delete newObj.response;
          delete newObj.raw;
          delete newObj.percentage;
          delete newObj.status;
          obj.url = response.data.data.url;
          delete newObj.response;
          return newObj;
        });
        this.form.zSign = JSON.stringify(updatedArray);//写入专家签到表

        if(this.filesLength2 > 0 && this.form.zCensor == null){
          this.$refs.upload2.submit();
        }else
        if(this.filesLength3 > 0 && this.form.zReview == null){
          this.$refs.upload3.submit();
        }else
        if(this.filesLength4 > 0 && this.form.zSummary == null){
          this.$refs.upload4.submit();
        }else{
          //执行操作
          if(this.isType ==='update'){
            //修改公告
            updateBidRules(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
              this.cancel();
            });
          }else if (this.isType ==='add'){
            addBidRules(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
              this.cancel();
            });
          }
          //修改招标项目状态
          this.upTender();
        }
      }
      this.upload.isUploading = false;
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`).then(res=>{
        this.form.zSign=null;
        this.upload.fileList = [];
      });
    },
    beforeUpload(file) {
      const isLt5M = file.size / 1024 / 1024 < 100;
      if (!isLt5M) {
        this.$message.error('文件大小不能超过100MB');
      }
      return isLt5M;
    },

    /** 审查表 */
    // 文件上传中处理
    handleFileUploadProgress1(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 修改当前文件列表长度
    changeFileLength1(file, fileList){
      this.filesLength2 = fileList.length;
    },
    // 文件上传成功处理
    handleFileSuccess1(response, file, fileList) {
      this.uploadFiles2.push(file);
      //每上传完一个文件都会执行该函数，所以必须等上传完成后再提交表单
      if (this.uploadFiles2.length == this.filesLength2){
        //已上传文件  --> 字符串
        let updatedArray = fileList.map(obj => {
          let newObj = obj;
          delete newObj.response;
          delete newObj.raw;
          delete newObj.percentage;
          delete newObj.status;
          obj.url = response.data.data.url;
          delete newObj.response;
          return newObj;
        });
        this.form.zCensor = JSON.stringify(updatedArray);

        if(this.filesLength > 0 && this.form.zSign == null){
          this.$refs.upload.submit();
        }else
        if(this.filesLength3 > 0 && this.form.zReview == null){
          this.$refs.upload3.submit();
        }else
        if(this.filesLength4 > 0 && this.form.zSummary == null){
          this.$refs.upload4.submit();
        }else{
          //执行操作
          if(this.isType ==='update'){
            //修改公告
            updateBidRules(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
              this.cancel();
            });
          }else if (this.isType ==='add'){
            addBidRules(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
              this.cancel();
            });
          }
          //修改招标项目状态
          this.upTender();
        }
      }
      this.upload.isUploading = false;
    },
    beforeRemove1(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`).then(res=>{
        this.form.zCensor=null;
        this.upload.fileList2 = [];
      });
    },
    beforeUpload1(file) {
      const isLt5M = file.size / 1024 / 1024 < 100;

      if (!isLt5M) {
        this.$message.error('文件大小不能超过100MB');
      }
      return isLt5M;
    },

    /** 评审表 */
    // 文件上传中处理
    handleFileUploadProgress2(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 修改当前文件列表长度
    changeFileLength2(file, fileList){
      this.filesLength3 = fileList.length;
    },
    // 文件上传成功处理
    handleFileSuccess2(response, file, fileList) {
      this.uploadFiles3.push(file);
      //每上传完一个文件都会执行该函数，所以必须等上传完成后再提交表单
      if (this.uploadFiles3.length === this.filesLength3){
        //已上传文件  --> 字符串
        let updatedArray = fileList.map(obj => {
          let newObj = obj;
          delete newObj.response;
          delete newObj.raw;
          delete newObj.percentage;
          delete newObj.status;
          obj.url = response.data.data.url;
          delete newObj.response;
          return newObj;
        });
        this.form.zReview = JSON.stringify(updatedArray);
        if(this.filesLength > 0 && this.form.zSign == null){
          this.$refs.upload.submit();
        }else
        if(this.filesLength2 > 0 && this.form.zCensor == null){
          this.$refs.upload2.submit();
        }else
        if(this.filesLength4 > 0 && this.form.zSummary == null){
          this.$refs.upload4.submit();
        }else{
          //执行操作
          if(this.isType ==='update'){
            //修改公告
            updateBidRules(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
              this.cancel();
            });
          }else if (this.isType ==='add'){
            addBidRules(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
              this.cancel();
            });
          }
          //修改招标项目状态
          this.upTender();
        }
      }
      this.upload.isUploading = false;
    },
    beforeRemove2(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`).then(res=>{
        this.upload.fileList3 = [];
        this.form.zReview=null;
      });
    },
    beforeUpload2(file) {
      const isLt5M = file.size / 1024 / 1024 < 100;

      if (!isLt5M) {
        this.$message.error('文件大小不能超过100MB');
      }
      return isLt5M;
    },

    /** 最终汇总表 */
    // 文件上传中处理
    handleFileUploadProgress3(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 修改当前文件列表长度
    changeFileLength3(file, fileList){
      this.filesLength4 = fileList.length;
    },
    // 文件上传成功处理
    handleFileSuccess3(response, file, fileList) {
      //拿到招标项目id
      this.form.sid = this.$route.query.sid;
      this.uploadFiles4.push(file);
      //每上传完一个文件都会执行该函数，所以必须等上传完成后再提交表单
      if (this.uploadFiles4.length === this.filesLength4){
        //已上传文件  --> 字符串
        let updatedArray = fileList.map(obj => {
          let newObj = obj;
          delete newObj.response;
          delete newObj.raw;
          delete newObj.percentage;
          delete newObj.status;
          obj.url = response.data.data.url;
          delete newObj.response;
          return newObj;
        });
        this.form.zSummary = JSON.stringify(updatedArray);

        if(this.filesLength > 0 && this.form.zSign == null){
          this.$refs.upload.submit();
        }else
        if(this.filesLength2 > 0 && this.form.zCensor == null){
          this.$refs.upload2.submit();
        }else
        if(this.filesLength3 > 0 && this.form.zReview == null){
          this.$refs.upload3.submit();
        }else{
          //执行操作
          if(this.isType ==='update'){
            //修改公告
            updateBidRules(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
              this.cancel();
            });
          }else if (this.isType ==='add'){
            addBidRules(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
              this.cancel();
            });
          }
          //修改招标项目状态
          this.upTender();
        }
      }
      this.upload.isUploading = false;
    },
    beforeRemove3(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`).then(res=>{
        this.form.zSummary=null;
        this.upload.fileList4 = [];
      });
    },
    beforeUpload3(file) {
      const isLt5M = file.size / 1024 / 1024 < 100;

      if (!isLt5M) {
        this.$message.error('文件大小不能超过100MB');
      }
      return isLt5M;
    },
  }
};
</script>
<style scoped>
.box {
  margin: 10px 0 15px 0px;
  color: #0065B5;
  font-size: 16px;
  font-weight: bold;
}
.form-input{
  width: 500px;
  display: inline-block;
}
</style>
